package com.qf.service;

import com.qf.constant.CacheConstants;
import com.qf.feign.CacheFeign;
import com.qf.model.StandardSubmit;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 实现扣费过滤策略
 * <p>
 * "phase,black,limitFiveMinutes,dirtyWords,fee,router".split(,)
 */
@Service("fee")
@Slf4j
public class FeeFilterServiceImpl implements FilterChainService {

    @Autowired
    private CacheFeign cacheFeign;

    /**
     * 实现扣费过滤策略
     *
     * @param standardSubmit
     * @return
     */
    @Override
    public boolean strategy(StandardSubmit standardSubmit) {
        System.out.println("======实现扣费过滤策略====");
/*    - 扣费 :  从缓存查询用户的单价，扣取用户所充值的费用
      - 如果费用不足就把发送日志存到Elasticsearch
      - 如果同时是HTTP的发送方式就模拟出状态报告推送给客户
*/
        String key = CacheConstants.CACHE_PREFIX_CLIENT + standardSubmit.getClientID();
        //1.查询当前客户存储在缓存中的剩余费用
        Object feeobject = cacheFeign.hget(key, "fee");
        Long fee = Long.parseLong(String.valueOf(feeobject));
        //2.查询当前短信需要的费用
        Long messageFee = standardSubmit.getFee();
        //3.判断客户剩余费用>=短信所需要费用
        if (fee >= messageFee) {
            //4.满足要求，开始扣费   hincr自增
            //Long hincrFee=fee-messageFee;
            Long hincrFee = cacheFeign.hincr(key, "fee", -messageFee);
            //5.扣费完成之后，显示用户剩余金额
            if (hincrFee < 0) {
                //6.如果扣除后金额<0   用户余额不足，将扣除的费用在加回缓存，记录日志，发送消息
                log.info("[策略模块 - 扣费策略] 扣费策略执行失败!!!用户剩余金额不足。。。剩余金额为："+fee);
                cacheFeign.hincr(key, "fee", messageFee);
                return false;
            }
            //7.如果发送成功，记录预扣除的费用(冻结费用)  冻结费用的key CUSTOMER_FEE：拼接上客户的ID
            cacheFeign.incr(CacheConstants.CACHE_PREFIX_CUSTOMER_FEE+standardSubmit.getClientID(), messageFee);
            log.info("[策略模块 - 扣费策略] 扣费策略执行成功！！！");
            System.out.println("[策略模块 - 扣费策略] 扣费策略执行成功！！！成功扣费："+messageFee+"剩余费用："+(fee-messageFee));
            return true;
        }
        return false;
    }
}
